<template>
  <div class="login">
    <van-nav-bar title="黑屋餐厅客户端">
    </van-nav-bar>
    <div v-if="tabsflag" id="wx_qrcode"></div>

    <div class="loginimg" v-if="!tabsflag">
      <img src="../../assets/img/logo.png" alt />
      <p>偶遇一场意想不到的邂逅</p>
    </div>
    <div class="logininp" v-if="!tabsflag">
      <van-field v-model="sms" center maxlength="11" type="number" clearable label="" placeholder="请输入手机号">
        <template #button>
          <van-button size="small" @click="getsms" :disabled="disabled" color="#55A79A" type="primary">{{modelcode}}</van-button>
        </template>
      </van-field>
      <van-field v-model="smsCode" placeholder="请输入验证码" class="user" />
      <van-button type="primary" size="large" color="#55A79A" @click="loginsms" class="loginbtn">登录</van-button>
      <div class="footer">
        <p class="register">没有账号？ <span @click="goRegister" src="/my">去注册</span></p>
      </div>
    </div>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import { getLoginVerifyCode, sendVerificationCode,testWepay} from "@/api/login"
import cryptojs from "crypto-js";
//防抖
function debounce(func, wait=1000){ //可以放入项目中的公共方法中进行调用（鹅只是省事）
 let timeout;
 return function(event){
  clearTimeout(timeout)
  timeout = setTimeout(()=>{
   func.call(this, event)
  },wait)
 }
}
export default {
  name: "login",
  components: {},
  data() {
    return {
      username: "",
      password: "",
      sms:"",
      smsCode:"",
      disabled:true,
      needImageVerifyCode: "",
      modelcode: "发送验证码",
      num: 60,
      inteval: null,
      codekeys: '',
      tabsflag: false,
      iframe: '',
      nums: 0,

    };
  },
  watch:{
    sms(oldval){
      if(oldval.length == 11 && this.num == 60){
        this.disabled = false
      } else {
        this.disabled = true
      }
    }
  },
  created() {
    

  },
  mounted() {
  },
  computed: {},
  props: [],
  methods: {
    testPay(){
      testWepay().then(res => {
        //alert(res.data);
        window.location.href=res.data;
      });
    },
    login() {
      if (!this.username) {
        this.$toast("请输入用户名");
        return;
      } else if (!this.password) {
        this.$toast("请输入密码");
        return;
      }
      let password = "";

      password = cryptojs.MD5(this.password).toString();

      this.LOGIN({
        userName: this.username,
        userPassword: password,
        loginType: 1,
      }).then(() => {
        this.$router.push("/orderlist");
      });
    },
    getsms(){ // 获取短信验证码
      this.disabled = true;
      this.num = 60
      this.inteval = setInterval(() => {
        this.num-=1;
        this.modelcode = `重新获取（${this.num}S）`;
        if(this.num<=0){
          clearInterval(this.inteval)
          if(this.sms.length == 11){
            this.disabled = false;
          } else {
            this.disabled = true;
          }
          this.modelcode = "发送验证码"
        }
      }, 1000);
      sendVerificationCode({
        mobile: this.sms,
        content: '正在申请短信登录黑屋餐厅客户端'
      }).then(res => {
        if(res.code == 200){
          this.codekeys = res.data;
        }
      })
    },
    goRegister(){
      this.$router.push('/register')
    },
    tabs(){
      this.tabsflag = !this.tabsflag;
      if(this.tabsflag){
        setTimeout(()=>{
          this.createIframe()
        },1)
      } else {
        this.removeIframe()
      }
    },
     createIframe () {
      let url = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=ww1f12664dcc690506&agentid=1000014&redirect_uri=https://noa-tst.lecarlink.com&href=data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30KLmltcG93ZXJCb3ggLmluZm8ge3dpZHRoOiAyMDBweDt9Ci5pbXBvd2VyQm94IC5zdGF0dXMge3RleHQtYWxpZ246IGNlbnRlcjt9`
        this.iframe = document.createElement('iframe')
        this.iframe.src = url
        this.iframe.frameBorder = '0'
        this.iframe.allowTransparency = 'true'
        this.iframe.scrolling = 'no'
        this.iframe.width = '250px'
        this.iframe.height = '400px'
        document.querySelector("#wx_qrcode").appendChild(this.iframe)
        this.iframe.onload = () => {
        if (this.iframe.contentWindow && this.iframe.contentWindow.postMessage && window.addEventListener) {
          window.addEventListener( 'message', evt => this.listener(evt), false)
          this.iframe.contentWindow.postMessage('ask_usePostMessage', '*')
        }
      }
    },
listener (event) {
    var that = this
    if (event.data && event.origin.indexOf('work.weixin.qq.com') > -1) {
    	// 接收登录成功的信息
      this.WX_CODE_LOGIN({
        code: String(event.data).split('&')[0].split('code=')[1],
        agentId: 1000014,
        loginType: 12,
        signData: '',
        signVal: ''
      }).then(res => {
        this.iframe.onload = null
        clearInterval(this.inteval)
        this.$router.push("/orderlist");
      })
      window.removeEventListener('message', evt => this.listener(evt), false)
    }
  },
    // 移除iframe
  removeIframe () {
    window.removeEventListener('message', evt => this.listener(evt), false)
    document.getElementById("wx_qrcode").removeChild(this.iframe)
    this.iframe = ''
  },
    loginsms:debounce(function(){
   if (!this.sms) {
        this.$toast("请输入正确的手机号");
        return;
      } else if (!this.smsCode) {
        this.$toast("请输入短信验证码");
        return;
      }
      // this.NEW_SMS_LOGIN({
      //   mobile: this.sms,
      //   verificationCodeKey: this.needImageVerifyCode,
      //   verifyCode: this.smsCode,
      // }).then(() => {
      //   clearInterval(this.inteval)
      //   this.$router.push("/hometab");
      // });
      this.WX_SMS_LOGIN({
        userName: this.sms,
        code: this.smsCode,
        key: this.codekeys,
        loginType: 12,
        signData: '',
        signVal: ''
      }).then(res => {
        clearInterval(this.inteval)
        this.$router.push("/orderlist");
      })
      this.smsCode = '';
  }),
    ...mapActions(["LOGIN"]),
    ...mapActions(["NEW_SMS_LOGIN"]),
    ...mapActions(["WX_SMS_LOGIN"]),
    ...mapActions(["WX_CODE_LOGIN"]),
  }
};
</script>

<style lang="scss">
.footer{
  width: 100%;
  text-align: center;
  padding-top: 10px;
  box-sizing: border-box;
}
.footer span{
  text-decoration: underline;
  color: #55A79A;
}
.register{
  font-size: 13px;
}
.login {
  width: 100%;
  height: 100%;
  background: #fff;
}
.logintitle {
  width: 100%;
  height: 43px;
  background: #ffffff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-around;
  box-sizing: border-box;
  p {
    font-size: 18px;
  }
}

.loginimg {
  background: #fff;
  width: 100%;
  text-align: center;
  box-sizing: border-box;
  padding: 58px 0 58px 0;
  img {
    width: 100px;
    height: 100px;
    display: inline-block;
  }
  p {
    font-family: PingFangSC-Semibold;
    font-size: 12px;
    color: #55A79A;
    letter-spacing: 0.8px;
    padding-top: 12px;
  }
}
.logininp {
  width: 100%;
  padding: 0 16px;
  box-sizing: border-box;
  background: #fff;
}
.loginbtn {
  margin-top: 28px;
}
.tabImg{
  width: 69px;
  position: absolute;
  top:46px;
  right: 0;
  cursor: pointer;
}
#wx_qrcode{
  display: flex;
  justify-content: center;
  margin-top: 20%;
}
</style>
